package com.invengo.module_check.ui.activity.login;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.invengo.base.router.RouterActivityPath;
import com.invengo.library_db.GreenDaoManager;
import com.invengo.library_rfid.entity.TagInfo;
import com.invengo.module_check.data.repsitory.common.CommonRepsitory;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.cache.ACache;
import me.goldze.mvvmhabit.utils.cache.AKey;

/**
 * @author buoker
 * @version 1.0.0
 * @date 2023/10/24
 * @className java.lang.String
 */

public class LoginViewModel extends BaseViewModel<CommonRepsitory> {
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>(ACache.getInstance().getAsString(AKey.CACHE_USERNAME));
    //密码的绑定
    public ObservableField<String> password = new ObservableField<>(ACache.getInstance().getAsString(AKey.CACHE_PASSWORD));
    public ObservableField<String> version = new ObservableField<>("");
    //用户名清除按钮的显示隐藏绑定
    public ObservableInt clearBtnVisibility = new ObservableInt();
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    private boolean autoLogin = ACache.getInstance().getAsBoolean(AKey.IS_AUTO_LOGIN);

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Boolean> adminEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Void> testEvent = new SingleLiveEvent<>();
    }

    public LoginViewModel(@NonNull Application application) {
        super(application, CommonRepsitory.getInstance());
        if (autoLogin)
            if (!TextUtils.isEmpty(password.get()) && !TextUtils.isEmpty(userName.get())) {
                new Handler().postDelayed(() -> {
                            if (!isLoging)
                                loginOnClickCommand.execute();
                        }
                        , 1500);
            }
      version.set("V "+getVerName(getApplication()));
    }


    //清除用户名的点击事件, 逻辑从View层转换到ViewModel层
    public BindingCommand clearUserNameOnClickCommand = new BindingCommand(() -> userName.set(""));
    //密码显示开关  (你可以尝试着狂按这个按钮,会发现它有防多次点击的功能)
    public BindingCommand passwordShowSwitchOnClickCommand = new BindingCommand(() -> {
        //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
        uc.pSwitchEvent.setValue(uc.pSwitchEvent.getValue() == null || !uc.pSwitchEvent.getValue());
//        version.set(getVersionCode(getApplication()));

    });
    //用户名输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusChangeCommand = new BindingCommand<>(hasFocus -> clearBtnVisibility.set(hasFocus ? View.VISIBLE : View.INVISIBLE));
    //登录按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(() -> {
        login();
    });

    private Long time = 0l;
    private int count = 1;
    private boolean isLaunchSetting = false;

    public void startSetting() {
        long timeNow = System.currentTimeMillis();
        if ((timeNow - time) < 1000) {
            count += 1;
            if (count > 2 && !isLaunchSetting && (7 - count) > 0)
                ToastUtils.showShort("再点击" + (7 - count) + "次进入设置界面");
        } else {
            count = 1;
        }
        time = timeNow;
        if (count >= 7) {
            isLaunchSetting = true;
            count = 1;
            uc.adminEvent.call();
        }
    }

    private boolean isLoging = false;

    /**
     * 网络模拟一个登陆操作
     **/
    private void login() {
        getUC().getHideKeyboardEvent().call();
        if (TextUtils.isEmpty(userName.get())) {
            ToastUtils.showShort("请输入账号！");
            return;
        }
        if (TextUtils.isEmpty(password.get())) {
            ToastUtils.showShort("请输入密码！");
            return;
        }
        isLoging = true;
        model.checkLogin(userName.get(), password.get())
                .compose(RxUtils.applySchedulersDialog(getLifecycleProvider(), this))
                .subscribe(userBean -> {
                    isLoging = false;
                    model.saveLoginUser(userName.get(), password.get(), userBean.getUserId());
                    ARouter.getInstance().build(RouterActivityPath.Check.PAGER_MAIN).navigation();
                    finish();
                });
    }


    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

}
